package com.mojang.minecraftpe;

import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.AlertDialog;
import android.app.NativeActivity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Debug;
import android.os.Environment;
import android.os.StatFs;
import android.os.SystemClock;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.provider.MediaStore.Images.Media;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.appsflyer.AppsFlyerLib;
import com.jxs.vblock.Logs;
import com.mojang.minecraftpe.TextInputProxyEditTextbox.MCPEKeyWatcher;

import org.fmod.FMOD;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

public class MainActivity extends NativeActivity implements OnKeyListener {
	public static int RESULT_GOOGLEPLAY_PURCHASE = 2;
	private static final int STORAGE_PERMISSION_ID = 1;
	public static int RESULT_PICK_IMAGE = STORAGE_PERMISSION_ID;
	private static boolean _isPowerVr = false;
	private static boolean mHasStoragePermission = false;
	private static final String mHockeyAppId = "3db796c2fc084bbc907764b7deb378c5";
	public static MainActivity mInstance = null;
	private final DateFormat DateFormat = new SimpleDateFormat();
	private boolean _fromOnCreate = false;
	private boolean _isTouchscreen = true;
	private int _userInputStatus = -1;
	private String[] _userInputText = null;
	//private ArrayList<StringValue> _userInputValues = new ArrayList<>();
	private int _viewDistance = 2;
	private ClipboardManager clipboardManager;
	private Bundle data;
	//private InputDeviceManager deviceManager;
	HeadsetConnectionReceiver headsetConnectionReceiver;
	private Locale initialUserLocale;
	//List<ActivityListener> mActivityListeners = new ArrayList<>();
	private long mCallback = 0;
	private AlertDialog mDialog;
	private long mFileDialogCallback = 0;
	PopupWindow mHiddenTextInputDialog;
	public int mLastPermissionRequestReason;
	//Platform platform;
	public String preloadingHTML = "<!doctype html><html><head><meta charset=\"utf-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\"><title>Log in</title><meta name=\"description\" content=\"\"><meta name=\"author\" content=\"\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1\"></head><body style=\"padding:0;margin:0;background:linear-gradient(#F9F9F9, #EEEEEE) repeat scroll 0 0 #F9F9F9;\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"width:100%;\"><tr style=\"height:40px;\"><td style=\"background: #111111;border:1px solid #333;\"><div style=\"margin:0 auto;width:320px;line-height:26px;\"><img style=\"width:120px;height:30px;float:left;margin-right:24px;vertical-align:middle;\" alt=\"\" src=\"\" /><div style=\"float:left;font-size:16px;font-weight:bold;color:#fff;font-family:Helvetica,Arial,sans-serif;text-shadow:0 -1px 1px #000000;\">Log in</div><div style=\"clear:both;\"></div></div></td></tr><tr style=\"height:235px;\"><td><div style=\"margin:0 auto;width:320px;text-align:center;font-family: Helvetica,Arial,sans-serif;text-shadow: 0 1px 0 #FFFFFF;font-size:24px;font-weight:bold;\">Loading&hellip;</div></td></tr><tr style=\"height:32px;\"><td style=\"background: #111111;border:1px solid #333;\"><div style=\"text-align:center;margin:0 auto;width:320px;line-height:26px;font-size:12px;font-weight:bold;color:#fff;font-family:Helvetica,Arial,sans-serif;text-shadow:0 -1px 1px #000000;\">Mojang &copy; 2013</div></td></tr></table></body></html>";
	TextInputProxyEditTextbox textInputWidget;
	private TextToSpeech textToSpeechManager;
	public int virtualKeyboardHeight = 0;

	private class HeadsetConnectionReceiver extends BroadcastReceiver {
		private HeadsetConnectionReceiver() {
		}

		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals("android.intent.action.HEADSET_PLUG")) {
				switch (intent.getIntExtra("state", -1)) {
					case 0:
						Logs.d(T, "Headset unplugged");
						MainActivity.this.nativeSetHeadphonesConnected(false);
						return;
					case 1:
						Logs.d(T, "Headset plugged in");
						MainActivity.this.nativeSetHeadphonesConnected(true);
						return;
					default:
						return;
				}
			}
		}
	}

	private native void setUpBreakpad(String str);

	native boolean isPublishBuild();

	native void nativeBackPressed();

	native void nativeBackSpacePressed();

	native boolean nativeKeyHandler(int i, int i2);

	native void nativeOnDestroy();

	native void nativeOnPickImageCanceled(long j);

	native void nativeOnPickImageSuccess(long j, String str);

	native void nativeProcessIntentUriQuery(String str, String str2);

	native void nativeRegisterThis();

	native void nativeReturnKeyPressed();

	native void nativeSetHeadphonesConnected(boolean z);

	native void nativeSetTextboxText(String str);

	native void nativeStopThis();

	native void nativeStoragePermissionRequestResult(boolean z, int i);

	native void nativeSuspend();

	native void nativeTypeCharacter(String str);

	native void nativeUnregisterThis();

	public void launchUri(String uri) {
		startActivity(new Intent("android.intent.action.VIEW", Uri.parse(uri)));
	}

	public void setClipboard(String value) {
		this.clipboardManager.setPrimaryClip(ClipData.newPlainText("MCPE-Clipdata", value));
	}

	public float getKeyboardHeight() {
		return (float) this.virtualKeyboardHeight;
	}

	public static final String T="VBlockCore";

	public void trackPurchaseEvent(String contentId, String contentType, String revenue, String playerId, String playerSessionId) {
		Map<String, Object> eventValue = new HashMap<>();
		eventValue.put("player_session_id", playerSessionId);
		eventValue.put("client_id", playerId);
		eventValue.put("af_revenue", revenue);
		eventValue.put("af_content_type", contentType);
		eventValue.put("af_content_id", contentId);
		AppsFlyerLib.getInstance().trackEvent(getApplicationContext(), "af_purchase", eventValue);
	}
	/*private boolean UseFake = false;
	@Override
	public PackageManager getPackageManager() {
		if (UseFake) return (PackageManager) FakePackageManager.getInstance(super.getPackageManager(), Global.MCPE_LIBDIR.getAbsolutePath());
		return super.getPackageManager();
	}*/

	public void onCreate(Bundle savedInstanceState) {
		//UseFake = true;
		super.onCreate(savedInstanceState);
		//UseFake = false;
		//this.platform = Platform.createPlatform(true);
		setVolumeControlStream(3);
		nativeRegisterThis();
		FMOD.init(this);
		//this.deviceManager = InputDeviceManager.create(this);
		//this.platform.onAppStart(getWindow().getDecorView());
		mHasStoragePermission = ContextCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE") == 0;
		this.headsetConnectionReceiver = new HeadsetConnectionReceiver();
		nativeSetHeadphonesConnected(((AudioManager) getSystemService("audio")).isWiredHeadsetOn());
		this.clipboardManager = (ClipboardManager) getSystemService("clipboard");
		this.initialUserLocale = Locale.getDefault();
		mInstance = this;
		this._fromOnCreate = true;
	}

	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getCharacters() != null) {
			nativeTypeCharacter(event.getCharacters());
		}
		if (nativeKeyHandler(event.getKeyCode(), event.getAction())) {
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	public void setTextToSpeechEnabled(boolean enabled) {
		if (!enabled) {
			this.textToSpeechManager = null;
		} else if (this.textToSpeechManager == null) {
			try {
				this.textToSpeechManager = new TextToSpeech(getApplicationContext(), new OnInitListener() {
						public void onInit(int status) {
						}
					});
			} catch (Exception e) {
			}
		}
	}

	public void requestStoragePermission(int permissionReason) {
		String[] permissions = new String[STORAGE_PERMISSION_ID];
		permissions[0] = "android.permission.WRITE_EXTERNAL_STORAGE";
		this.mLastPermissionRequestReason = permissionReason;
		ActivityCompat.requestPermissions(this, permissions, STORAGE_PERMISSION_ID);
	}

	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		if (requestCode == STORAGE_PERMISSION_ID) {
			if (grantResults[0] == 0) {
				mHasStoragePermission = true;
			} else {
				mHasStoragePermission = false;
			}
			nativeStoragePermissionRequestResult(mHasStoragePermission, this.mLastPermissionRequestReason);
		}
	}

	public boolean hasWriteExternalStoragePermission() {
		mHasStoragePermission = ContextCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE") == 0;
		return mHasStoragePermission;
	}

	public void setupKeyboardViews(String text, int maxLength, boolean limitInput, boolean numbersOnly) {
		this.textInputWidget = new TextInputProxyEditTextbox(this, maxLength, limitInput);
		this.textInputWidget.setFocusable(true);
		this.textInputWidget.setFocusableInTouchMode(true);
		this.textInputWidget.setInputType(655360);
		this.textInputWidget.setImeOptions(268435461);
		this.textInputWidget.setText(text);
		if (numbersOnly) {
			this.textInputWidget.setInputType(2);
		}
		this.textInputWidget.setOnEditorActionListener(new OnEditorActionListener() {
				public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
					Logs.v(T, "onEditorAction: " + actionId);
					if (actionId == 5) {
						MainActivity.this.nativeReturnKeyPressed();
						String curText = MainActivity.this.textInputWidget.getText().toString();
						int curSelect = MainActivity.this.textInputWidget.getSelectionEnd();
						MainActivity.this.textInputWidget.setText(curText.substring(0, curSelect) + "\n" + curText.substring(curSelect, curText.length()));
						MainActivity.this.textInputWidget.setSelection(curSelect + MainActivity.STORAGE_PERMISSION_ID);
						return true;
					} else if (actionId != 7) {
						return false;
					} else {
						MainActivity.this.nativeBackPressed();
						return true;
					}
				}
			});
		this.textInputWidget.addTextChangedListener(new TextWatcher() {
				public void onTextChanged(CharSequence s, int start, int before, int count) {
				}

				public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				}

				public void afterTextChanged(Editable s) {
					MainActivity.this.nativeSetTextboxText(s.toString());
				}
			});
		this.textInputWidget.setOnMCPEKeyWatcher(new MCPEKeyWatcher() {
				public void onDeleteKeyPressed() {
					MainActivity.this.runOnUiThread(new Runnable() {
							public void run() {
								MainActivity.this.nativeBackSpacePressed();
							}
						});
				}
				public void onBackKeyPressed() {
					MainActivity.this.runOnUiThread(new Runnable() {
							public void run() {
								Logs.v(T, "textInputWidget.onBackPressed");
								MainActivity.this.nativeBackPressed();
							}
						});
				}
			});
		this.mHiddenTextInputDialog = new PopupWindow(this);
		this.mHiddenTextInputDialog.setInputMethodMode(STORAGE_PERMISSION_ID);
		this.mHiddenTextInputDialog.setWidth(320);
		this.mHiddenTextInputDialog.setHeight(50);
		this.mHiddenTextInputDialog.setWindowLayoutMode(-2, -2);
		this.mHiddenTextInputDialog.setClippingEnabled(false);
		LinearLayout layout = new LinearLayout(this);
		LinearLayout mainLayout = new LinearLayout(this);
		layout.setPadding(-5, -5, -5, -5);
		MarginLayoutParams params = new MarginLayoutParams(-2, -2);
		params.setMargins(0, 0, 0, 0);
		layout.setOrientation(LinearLayout.VERTICAL);
		layout.addView(this.textInputWidget, params);
		this.mHiddenTextInputDialog.setContentView(layout);
		setContentView(mainLayout, params);
		this.mHiddenTextInputDialog.setOutsideTouchable(true);
		this.mHiddenTextInputDialog.setTouchInterceptor(new OnTouchListener() {
				public boolean onTouch(View v, MotionEvent event) {
					MainActivity.this.nativeBackPressed();
					return false;
				}
			});
		this.mHiddenTextInputDialog.showAtLocation(mainLayout, 0, -50000, 0);
		this.mHiddenTextInputDialog.setFocusable(true);
		this.mHiddenTextInputDialog.update();
		this.mHiddenTextInputDialog.dismiss();
		this.mHiddenTextInputDialog.showAtLocation(mainLayout, 0, -50000, 0);
		this.mHiddenTextInputDialog.setFocusable(true);
		this.mHiddenTextInputDialog.update();
		this.textInputWidget.postDelayed(new Runnable() {
				public void run() {
					MotionEvent event = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), 0, 0.0f, 0.0f, 0);
					MainActivity.this.textInputWidget.dispatchTouchEvent(event);
					event.recycle();
					event = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MainActivity.STORAGE_PERMISSION_ID, 0.0f, 0.0f, 0);
					MainActivity.this.textInputWidget.dispatchTouchEvent(event);
					event.recycle();
					MainActivity.this.textInputWidget.setSelection(MainActivity.this.textInputWidget.length());
				}
			}, 200);
		final View activityRootView = findViewById(16908290).getRootView();
		activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
				public void onGlobalLayout() {
					Rect r = new Rect();
					activityRootView.getWindowVisibleDisplayFrame(r);
					MainActivity.this.virtualKeyboardHeight = activityRootView.getRootView().getHeight() - r.height();
				}
			});
	}

	public void updateLocalization(String lang, String region) {
		final String langString = lang;
		final String regionString = region;
		runOnUiThread(new Runnable() {
				public void run() {
					Locale locale = new Locale(langString, regionString);
					Locale.setDefault(locale);
					Configuration config = new Configuration();
					config.locale = locale;
					MainActivity.this.getResources().updateConfiguration(config, MainActivity.this.getResources().getDisplayMetrics());
				}
			});
	}

	public void showKeyboard(String text, int maxLength, boolean limitInput, boolean numbersOnly) {
		final String startText = text;
		final int fMaxLength = maxLength;
		final boolean fLimitInput = limitInput;
		final boolean fNumbersOnly = numbersOnly;
		runOnUiThread(new Runnable() {
				public void run() {
					MainActivity.this.setupKeyboardViews(startText, fMaxLength, fLimitInput, fNumbersOnly);
				}
			});
	}

	public void hideKeyboard() {
		runOnUiThread(new Runnable() {
				public void run() {
					if (MainActivity.this.mHiddenTextInputDialog != null) {
						MainActivity.this.mHiddenTextInputDialog.dismiss();
						MainActivity.this.mHiddenTextInputDialog = null;
					}
				}
			});
	}

	public void updateTextboxText(String newText) {
		final String setText = newText;
		runOnUiThread(new Runnable() {
				public void run() {
					if (MainActivity.this.textInputWidget == null) {
						MainActivity.this.setupKeyboardViews(setText, setText.length(), false, false);
					}
					MainActivity.this.textInputWidget.setText(setText);
					MainActivity.this.textInputWidget.setSelection(MainActivity.this.textInputWidget.length());
				}
			});
	}

	public int getCursorPosition() {
		if (this.mHiddenTextInputDialog == null || this.textInputWidget == null) {
			return -1;
		}
		return this.textInputWidget.getSelectionStart();
	}

	public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
		return super.onKeyMultiple(keyCode, repeatCount, event);
	}

	public boolean onKey(View v, int keyCode, KeyEvent event) {
		return false;
	}

	public void onBackPressed() {
	}

	public void setIsPowerVR(boolean status) {
		_isPowerVr = status;
	}

	public static boolean isPowerVR() {
		return _isPowerVr;
	}
	public int getKeyFromKeyCode(int keyCode, int metaState, int deviceId) {
		if (deviceId < 0) {
			int[] ids = InputDevice.getDeviceIds();
			if (ids.length == 0) {
				return 0;
			}
			deviceId = ids[0];
		}
		InputDevice device = InputDevice.getDevice(deviceId);
		if (device != null) {
			return device.getKeyCharacterMap().get(keyCode, metaState);
		}
		return 0;
	}
	public static void saveScreenshot(String filename, int w, int h, int[] pixels) {
		Bitmap bitmap = Bitmap.createBitmap(pixels, w, h, Config.ARGB_8888);
		try {
			FileOutputStream fos = new FileOutputStream(filename);
			bitmap.compress(CompressFormat.JPEG, 85, fos);
			try {
				fos.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				fos.close();
			} catch (IOException e2) {
				e2.printStackTrace();
			}
		} catch (FileNotFoundException e3) {
			Logs.e(T, "Couldn't create file: " + filename);
			e3.printStackTrace();
		}
	}
	public byte[] getFileDataBytes(String filename) {
		filename = filename.replace("com.mojang.minecraftpe", "com.jxs.vblock");
		Logs.i(T, "GetFileDataBytes:" + filename);
		//Logs.i(T, "getFileData:" + filename);
		/*byte[] bytes = getFileDataBytesInside(name, false);
		 if (!name.endsWith(".meta")) {
		 return bytes;
		 }
		 String fileStr = new String(bytes, Charset.forName("UTF-8"));
		 if (fileStr.contains("portal") || fileStr.contains("rabbit_foot")) {
		 return bytes;
		 }
		 return getFileDataBytesInside(name, true);*/
		if (filename.isEmpty()) return null;
		InputStream is=null;
		if (filename.charAt(0) == '/')
			try {
				is = new FileInputStream(new File(filename));
			} catch (IOException e) {
				//Logs.e(T, Logs.join("Cannot find file ", filename, " in external storage"));
				return null;
			}
		else 
			try {
				is = getAssets().open("filename");
			} catch (IOException e) {
				//Logs.i(T, Logs.join("Cannot find file ", filename, " in assets"));
				return null;
			}
		try {
			int MB=0x100000;
			ByteArrayOutputStream tmp=new ByteArrayOutputStream();
			byte[] buf=new byte[MB];
			int read=is.read(buf);
			tmp.write(buf, 0, read);
			buf = null;
			return tmp.toByteArray();
		} catch (IOException e) {
			//Logs.e(T, "Cannot read from InputStream:" + is);
			return null;
		}
	}
	public int[] getImageData(String filename) {
		filename = filename.replace("com.mojang.minecraftpe", "com.jxs.vblock");
		InputStream is;
		if (filename.charAt(0) == '/')
			try {
				is = new FileInputStream(new File(filename));
			} catch (IOException e) {
				return null;
			}
		else 
			try {
				is = getAssets().open(filename);
			} catch (IOException e) {
				return null;
			}
		Bitmap bm=BitmapFactory.decodeStream(is);
		int w = bm.getWidth();
		int h = bm.getHeight();
		int[] pixels = new int[((w * h) + 2)];
		pixels[0] = w;
		pixels[1] = h;
		bm.getPixels(pixels, 2, w, 0, 0, w, h);
		return pixels;
	}

	public int getScreenWidth() {
		Display display = ((WindowManager) getSystemService("window")).getDefaultDisplay();
		int out = Math.max(display.getWidth(), display.getHeight());
		return out;
	}

	public int getScreenHeight() {
		Display display = ((WindowManager) getSystemService("window")).getDefaultDisplay();
		int out = Math.min(display.getWidth(), display.getHeight());
		return out;
	}

	public int getAndroidVersion() {
		return VERSION.SDK_INT;
	}

	public String getDeviceModel() {
		return HardwareInformation.getDeviceModelName();
	}

	public String getLocale() {
		Locale locale = getResources().getConfiguration().locale;
		return locale.getLanguage() + "_" + locale.getCountry();
	}

	public String getExternalStoragePath() {
		return Environment.getExternalStorageDirectory().getAbsolutePath();
	}

	public float getPixelsPerMillimeter() {
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		return ((metrics.xdpi + metrics.ydpi) * 0.5f) / 25.4f;
	}
	public int checkLicense() {
		return 0;
	}
	public String getFormattedDateString(int s) {
		return DateFormat.getDateInstance(3, this.initialUserLocale).format(new Date(((long) s) * 1000));
	}
	public String getFileTimestamp(int s) {
		return new SimpleDateFormat("__EEE__yyyy_MM_dd__HH_mm_ss'.txt'").format(new Date(((long) s) * 1000));
	}
	public boolean hasBuyButtonWhenInvalidLicense() {
		return true;
	}
	public void postScreenshotToFacebook(String filename, int w, int h, int[] pixels) {}
	public void quit() {
		runOnUiThread(new Runnable() {
				public void run() {
					//MainActivity.this.finish();
				}
			});
	}
	public void displayDialog(int dialogId) {}

	public void tick() {}

	public void buyGame() {}

	public String getPlatformStringVar(int id) {
		if (id == 0)
			return Build.MODEL;
		return null;
	}

	public boolean isNetworkEnabled(boolean onlyWifiAllowed) {
		ConnectivityManager cm = (ConnectivityManager) getSystemService("connectivity");
		NetworkInfo info = cm.getNetworkInfo(9);
		if (info != null && info.isConnected()) {
			return true;
		}
		info = cm.getNetworkInfo(STORAGE_PERMISSION_ID);
		if (info != null && info.isConnected()) {
			return true;
		}
		info = cm.getActiveNetworkInfo();
		if (info == null || !info.isConnected() || onlyWifiAllowed) {
			return false;
		}
		return true;
	}

	public void setSession(String sessionId) {
		Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
		edit.putString("sessionID", sessionId);
		edit.commit();
	}

	public void setRefreshToken(String refreshToken) {
		Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
		edit.putString("refreshToken", refreshToken);
		edit.commit();
	}

	public void setLoginInformation(String accessToken, String clientId, String profileId, String profileName) {
		Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
		edit.putString("accessToken", accessToken);
		edit.putString("clientId", clientId);
		edit.putString("profileId", profileId);
		edit.putString("profileName", profileName);
		edit.commit();
	}

	public void clearLoginInformation() {
		Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
		edit.remove("accessToken");
		edit.remove("clientId");
		edit.remove("profileId");
		edit.remove("profileName");
		edit.commit();
	}

	public String getAccessToken() {
		return PreferenceManager.getDefaultSharedPreferences(this).getString("accessToken", "");
	}

	public String getClientId() {
		return PreferenceManager.getDefaultSharedPreferences(this).getString("clientId", "");
	}

	public String getProfileId() {
		return PreferenceManager.getDefaultSharedPreferences(this).getString("profileId", "");
	}

	public String getProfileName() {
		return PreferenceManager.getDefaultSharedPreferences(this).getString("profileName", "");
	}

	public void statsTrackEvent(String eventName, String eventParameters) {
	}

	public void statsUpdateUserData(String graphicsVendor, String graphicsRenderer) {
	}

	public String[] getBroadcastAddresses() {
		ArrayList<String> list = new ArrayList<>();
		try {
			System.setProperty("java.net.preferIPv4Stack", "true");
			Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces();
			while (niEnum.hasMoreElements()) {
				NetworkInterface ni = niEnum.nextElement();
				if (!ni.isLoopback()) {
					for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
						if (interfaceAddress.getBroadcast() != null) {
							list.add(interfaceAddress.getBroadcast().toString().substring(STORAGE_PERMISSION_ID));
						}
					}
				}
			}
		} catch (Exception e) {
		}
		return list.toArray(new String[list.size()]);
	}

	public String[] getIPAddresses() {
		ArrayList<String> list = new ArrayList<>();
		try {
			System.setProperty("java.net.preferIPv4Stack", "true");
			Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces();
			while (niEnum.hasMoreElements()) {
				NetworkInterface ni = niEnum.nextElement();
				if (!ni.isLoopback() && ni.isUp()) {
					for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
						InetAddress addr = interfaceAddress.getAddress();
						if (!(addr == null || addr.isAnyLocalAddress() || addr.isMulticastAddress() || addr.isLinkLocalAddress())) {
							list.add(interfaceAddress.getAddress().toString().substring(STORAGE_PERMISSION_ID));
						}
					}
				}
			}
		} catch (Exception e) {
		}
		return list.toArray(new String[list.size()]);
	}

	public void initiateUserInput(int id) {
		this._userInputText = null;
		this._userInputStatus = -1;
	}

	public int getUserInputStatus() {
		return this._userInputStatus;
	}

	public String[] getUserInputString() {
		return this._userInputText;
	}

	public void vibrate(int milliSeconds) {
		((Vibrator) getSystemService("vibrator")).vibrate((long) milliSeconds);
	}

	public long getTotalMemory() {
		ActivityManager activityManager = (ActivityManager) getSystemService("activity");
		MemoryInfo memoryInfo = new MemoryInfo();
		activityManager.getMemoryInfo(memoryInfo);
		return memoryInfo.totalMem;
	}

	public long getAvailableMemory() {
		ActivityManager activityManager = (ActivityManager) getSystemService("activity");
		MemoryInfo memoryInfo = new MemoryInfo();
		activityManager.getMemoryInfo(memoryInfo);
		return memoryInfo.availMem;
	}

	public long getUsedMemory() {
		return Debug.getNativeHeapAllocatedSize();
	}

	public long calculateAvailableDiskFreeSpace(String rootPath) {
		StatFs stat = new StatFs(rootPath);
		if (VERSION.SDK_INT >= 18) {
			return stat.getAvailableBytes();
		}
		return (long) (stat.getAvailableBlocks() * stat.getBlockSize());
	}

	protected void onResume() {
		Logs.d(T, "onResume");
		super.onResume();
		registerReceiver(this.headsetConnectionReceiver, new IntentFilter("android.intent.action.HEADSET_PLUG"));
		if (this.mHiddenTextInputDialog != null) {
			String oldText = this.textInputWidget.getText().toString();
			int maxNumCharacters = this.textInputWidget.allowedLength;
			boolean limitInput = this.textInputWidget.limitInput;
			boolean numbersOnly = (this.textInputWidget.getInputType() & 2) == 2;
			this.textInputWidget.getInputType();
			this.mHiddenTextInputDialog.dismiss();
			this.mHiddenTextInputDialog = null;
			showKeyboard(oldText, maxNumCharacters, limitInput, numbersOnly);
		}
	}

	protected void onPause() {
		Logs.d(T, "onPause");
		nativeSuspend();
		super.onPause();
	}

	protected void onStop() {
		Logs.d(T, "onStop");
		nativeStopThis();
		super.onStop();
	}

	protected void onDestroy() {
		Logs.d(T, "onDestroy");
		mInstance = null;
		Logs.i(T, "onDestroy");
		FMOD.close();
		nativeUnregisterThis();
		nativeOnDestroy();
		super.onDestroy();
		System.exit(0);
	}

	public void onNewIntent(Intent intent) {
		setIntent(intent);
		//processIntent(intent);
	}
	public byte[] getFileDataBytesInside(String name, boolean forceInternal) {
		try {
			java.io.InputStream is;
			if (name.charAt(0) == '/') {
				is = new BufferedInputStream(new FileInputStream(name));
			} else
				is = getAssets().open(name);
			if (is == null)
				return null;
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			while (true) {
				int len = is.read(buffer);
				if (len < 0) {
					return bout.toByteArray();
				}
				bout.write(buffer, 0, len);
			}
		} catch (Exception e) {
			return null;
		}
	}

	/* JADX WARNING: inconsistent code. */
	/* Code decompiled incorrectly, please refer to instructions dump. */
	/*private void processIntent(android.content.Intent r29) {
	 /*
	 r28 = this;
	 if (r29 != 0) goto L_0x0003;
	 L_0x0002:
	 return;
	 L_0x0003:
	 r24 = "intent_cmd";
	 r0 = r29;
	 r1 = r24;
	 r8 = r0.getStringExtra(r1);
	 if (r8 == 0) goto L_0x00af;
	 L_0x000f:
	 r24 = r8.length();
	 if (r24 <= 0) goto L_0x00af;
	 L_0x0015:
	 r14 = new org.json.JSONObject;	 Catch:{ JSONException -> 0x003c }
	 r14.<init>(r8);	 Catch:{ JSONException -> 0x003c }
	 r24 = "Command";
	 r0 = r24;
	 r6 = r14.getString(r0);	 Catch:{ JSONException -> 0x003c }
	 r24 = "keyboardResult";
	 r0 = r24;
	 r24 = r6.equals(r0);	 Catch:{ JSONException -> 0x003c }
	 if (r24 == 0) goto L_0x005a;
	 L_0x002c:
	 r24 = "Text";
	 r0 = r24;
	 r24 = r14.getString(r0);	 Catch:{ JSONException -> 0x003c }
	 r0 = r28;
	 r1 = r24;
	 r0.nativeSetTextboxText(r1);	 Catch:{ JSONException -> 0x003c }
	 goto L_0x0002;
	 L_0x003c:
	 r7 = move-exception;
	 r24 = "MCPE";
	 r25 = new java.lang.StringBuilder;
	 r25.<init>();
	 r26 = "JSONObject exception:";
	 r25 = r25.append(r26);
	 r26 = r7.toString();
	 r25 = r25.append(r26);
	 r25 = r25.toString();
	 android.util.Log.d(r24, r25);
	 goto L_0x0002;
	 L_0x005a:
	 r24 = "fileDialogResult";
	 r0 = r24;
	 r24 = r6.equals(r0);	 Catch:{ JSONException -> 0x003c }
	 if (r24 == 0) goto L_0x0002;
	 L_0x0064:
	 r0 = r28;
	 r0 = r0.mFileDialogCallback;	 Catch:{ JSONException -> 0x003c }
	 r24 = r0;
	 r26 = 0;
	 r24 = (r24 > r26 ? 1 : (r24 == r26 ? 0 : -1));
	 if (r24 == 0) goto L_0x0002;
	 L_0x0070:
	 r24 = "Result";
	 r0 = r24;
	 r24 = r14.getString(r0);	 Catch:{ JSONException -> 0x003c }
	 r25 = "Ok";
	 r24 = r24.equals(r25);	 Catch:{ JSONException -> 0x003c }
	 if (r24 == 0) goto L_0x00a1;
	 L_0x0080:
	 r0 = r28;
	 r0 = r0.mFileDialogCallback;	 Catch:{ JSONException -> 0x003c }
	 r24 = r0;
	 r26 = "Path";
	 r0 = r26;
	 r26 = r14.getString(r0);	 Catch:{ JSONException -> 0x003c }
	 r0 = r28;
	 r1 = r24;
	 r3 = r26;
	 r0.nativeOnPickImageSuccess(r1, r3);	 Catch:{ JSONException -> 0x003c }
	 L_0x0097:
	 r24 = 0;
	 r0 = r24;
	 r2 = r28;
	 r2.mFileDialogCallback = r0;	 Catch:{ JSONException -> 0x003c }
	 goto L_0x0002;
	 L_0x00a1:
	 r0 = r28;
	 r0 = r0.mFileDialogCallback;	 Catch:{ JSONException -> 0x003c }
	 r24 = r0;
	 r0 = r28;
	 r1 = r24;
	 r0.nativeOnPickImageCanceled(r1);	 Catch:{ JSONException -> 0x003c }
	 goto L_0x0097;
	 L_0x00af:
	 r4 = r29.getAction();
	 r22 = r29.getType();
	 r24 = "xbox_live_game_invite";
	 r0 = r24;
	 r24 = r0.equals(r4);
	 if (r24 == 0) goto L_0x00ec;
	 L_0x00c1:
	 r24 = "xbl";
	 r0 = r29;
	 r1 = r24;
	 r14 = r0.getStringExtra(r1);
	 r24 = "MCPE";
	 r25 = new java.lang.StringBuilder;
	 r25.<init>();
	 r26 = "[XboxLive] Received Invite ";
	 r25 = r25.append(r26);
	 r0 = r25;
	 r25 = r0.append(r14);
	 r25 = r25.toString();
	 android.util.Log.d(r24, r25);
	 r0 = r28;
	 r0.nativeProcessIntentUriQuery(r4, r14);
	 goto L_0x0002;
	 L_0x00ec:
	 r24 = "android.intent.action.VIEW";
	 r0 = r24;
	 r24 = r0.equals(r4);
	 if (r24 == 0) goto L_0x0002;
	 L_0x00f6:
	 r18 = r29.getScheme();
	 r23 = r29.getData();
	 if (r23 == 0) goto L_0x0002;
	 L_0x0100:
	 r24 = "minecraft";
	 r0 = r24;
	 r1 = r18;
	 r24 = r0.equalsIgnoreCase(r1);
	 if (r24 == 0) goto L_0x0121;
	 L_0x010c:
	 r10 = r23.getHost();
	 r16 = r23.getQuery();
	 if (r10 != 0) goto L_0x0118;
	 L_0x0116:
	 if (r16 == 0) goto L_0x0002;
	 L_0x0118:
	 r0 = r28;
	 r1 = r16;
	 r0.nativeProcessIntentUriQuery(r10, r1);
	 goto L_0x0002;
	 L_0x0121:
	 r24 = "file";
	 r0 = r24;
	 r1 = r18;
	 r24 = r0.equalsIgnoreCase(r1);
	 if (r24 == 0) goto L_0x0159;
	 L_0x012d:
	 r24 = "fileIntent";
	 r25 = new java.lang.StringBuilder;
	 r25.<init>();
	 r26 = r23.getPath();
	 r25 = r25.append(r26);
	 r26 = "&";
	 r25 = r25.append(r26);
	 r26 = r23.getPath();
	 r25 = r25.append(r26);
	 r25 = r25.toString();
	 r0 = r28;
	 r1 = r24;
	 r2 = r25;
	 r0.nativeProcessIntentUriQuery(r1, r2);
	 goto L_0x0002;
	 L_0x0159:
	 r24 = "content";
	 r0 = r24;
	 r1 = r18;
	 r24 = r0.equalsIgnoreCase(r1);
	 if (r24 == 0) goto L_0x0002;
	 L_0x0165:
	 r24 = new java.io.File;
	 r25 = r23.getPath();
	 r24.<init>(r25);
	 r9 = r24.getName();
	 r20 = new java.io.File;
	 r24 = new java.lang.StringBuilder;
	 r24.<init>();
	 r25 = r28.getApplicationContext();
	 r25 = r25.getCacheDir();
	 r24 = r24.append(r25);
	 r25 = "/";
	 r24 = r24.append(r25);
	 r0 = r24;
	 r24 = r0.append(r9);
	 r24 = r24.toString();
	 r0 = r20;
	 r1 = r24;
	 r0.<init>(r1);
	 r17 = r28.getContentResolver();
	 r0 = r17;
	 r1 = r23;
	 r11 = r0.openInputStream(r1);	 Catch:{ IOException -> 0x0215 }
	 r15 = new java.io.FileOutputStream;	 Catch:{ IOException -> 0x01d1 }
	 r0 = r20;
	 r15.<init>(r0);	 Catch:{ IOException -> 0x01d1 }
	 r19 = 0;
	 r5 = 1048576; // 0x100000 float:1.469368E-39 double:5.180654E-318;
	 r0 = new byte[r5];	 Catch:{ IOException -> 0x01d1 }
	 r21 = r0;
	 L_0x01b7:
	 r0 = r21;
	 r19 = r11.read(r0);	 Catch:{ IOException -> 0x01d1 }
	 r24 = -1;
	 r0 = r19;
	 r1 = r24;
	 if (r0 == r1) goto L_0x0234;
	 L_0x01c5:
	 r24 = 0;
	 r0 = r21;
	 r1 = r24;
	 r2 = r19;
	 r15.write(r0, r1, r2);	 Catch:{ IOException -> 0x01d1 }
	 goto L_0x01b7;
	 L_0x01d1:
	 r12 = move-exception;
	 r24 = "MCPE";
	 r25 = new java.lang.StringBuilder;	 Catch:{ all -> 0x0285 }
	 r25.<init>();	 Catch:{ all -> 0x0285 }
	 r26 = "IOException while copying file from content intent\n";
	 r25 = r25.append(r26);	 Catch:{ all -> 0x0285 }
	 r26 = r12.toString();	 Catch:{ all -> 0x0285 }
	 r25 = r25.append(r26);	 Catch:{ all -> 0x0285 }
	 r25 = r25.toString();	 Catch:{ all -> 0x0285 }
	 android.util.Log.e(r24, r25);	 Catch:{ all -> 0x0285 }
	 r20.delete();	 Catch:{ Exception -> 0x02a8 }
	 L_0x01f1:
	 r11.close();	 Catch:{ IOException -> 0x01f6 }
	 goto L_0x0002;
	 L_0x01f6:
	 r13 = move-exception;
	 r24 = "MCPE";
	 r25 = new java.lang.StringBuilder;
	 r25.<init>();
	 r26 = "IOException while closing input stream\n";
	 r25 = r25.append(r26);
	 r26 = r13.toString();
	 r25 = r25.append(r26);
	 r25 = r25.toString();
	 android.util.Log.e(r24, r25);
	 goto L_0x0002;
	 L_0x0215:
	 r12 = move-exception;
	 r24 = "MCPE";
	 r25 = new java.lang.StringBuilder;
	 r25.<init>();
	 r26 = "IOException while opening file from content intent\n";
	 r25 = r25.append(r26);
	 r26 = r12.toString();
	 r25 = r25.append(r26);
	 r25 = r25.toString();
	 android.util.Log.e(r24, r25);
	 goto L_0x0002;
	 L_0x0234:
	 r15.close();	 Catch:{ IOException -> 0x01d1 }
	 r24 = "contentIntent";
	 r25 = new java.lang.StringBuilder;	 Catch:{ IOException -> 0x01d1 }
	 r25.<init>();	 Catch:{ IOException -> 0x01d1 }
	 r26 = r23.getPath();	 Catch:{ IOException -> 0x01d1 }
	 r25 = r25.append(r26);	 Catch:{ IOException -> 0x01d1 }
	 r26 = "&";
	 r25 = r25.append(r26);	 Catch:{ IOException -> 0x01d1 }
	 r26 = r20.getAbsolutePath();	 Catch:{ IOException -> 0x01d1 }
	 r25 = r25.append(r26);	 Catch:{ IOException -> 0x01d1 }
	 r25 = r25.toString();	 Catch:{ IOException -> 0x01d1 }
	 r0 = r28;
	 r1 = r24;
	 r2 = r25;
	 r0.nativeProcessIntentUriQuery(r1, r2);	 Catch:{ IOException -> 0x01d1 }
	 r11.close();	 Catch:{ IOException -> 0x0266 }
	 goto L_0x0002;
	 L_0x0266:
	 r13 = move-exception;
	 r24 = "MCPE";
	 r25 = new java.lang.StringBuilder;
	 r25.<init>();
	 r26 = "IOException while closing input stream\n";
	 r25 = r25.append(r26);
	 r26 = r13.toString();
	 r25 = r25.append(r26);
	 r25 = r25.toString();
	 android.util.Log.e(r24, r25);
	 goto L_0x0002;
	 L_0x0285:
	 r24 = move-exception;
	 r11.close();	 Catch:{ IOException -> 0x028a }
	 L_0x0289:
	 throw r24;
	 L_0x028a:
	 r13 = move-exception;
	 r25 = "MCPE";
	 r26 = new java.lang.StringBuilder;
	 r26.<init>();
	 r27 = "IOException while closing input stream\n";
	 r26 = r26.append(r27);
	 r27 = r13.toString();
	 r26 = r26.append(r27);
	 r26 = r26.toString();
	 android.util.Log.e(r25, r26);
	 goto L_0x0289;
	 L_0x02a8:
	 r24 = move-exception;
	 goto L_0x01f1;
	 *
	 throw new UnsupportedOperationException("Method not decompiled: com.mojang.minecraftpe.MainActivity.processIntent(android.content.Intent):void");
	 }*/

	protected boolean isDemo() {
		return false;
	}

	public boolean isFirstSnooperStart() {
		return PreferenceManager.getDefaultSharedPreferences(this).getString("snooperId", "").isEmpty();
	}

	public String createDeviceID() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		String snooperID = prefs.getString("snooperId", "");
		if (!snooperID.isEmpty()) {
			return snooperID;
		}
		snooperID = UUID.randomUUID().toString().replaceAll("-", "");
		Editor edit = prefs.edit();
		edit.putString("snooperId", snooperID);
		edit.commit();
		return snooperID;
	}

	public String createUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	public Intent createAndroidLaunchIntent() {
		Context context = getApplicationContext();
		return context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
	}

	boolean hasHardwareChanged() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		String lastAndroidVersion = prefs.getString("lastAndroidVersion", "");
		boolean firstHardwareStart = lastAndroidVersion.isEmpty() || !lastAndroidVersion.equals(VERSION.RELEASE);
		if (firstHardwareStart) {
			Editor edit = prefs.edit();
			edit.putString("lastAndroidVersion", VERSION.RELEASE);
			edit.commit();
		}
		return firstHardwareStart;
	}

	public boolean isTablet() {
		return (getResources().getConfiguration().screenLayout & 15) == 4;
	}

	public void pickImage(long callback) {
		this.mCallback = callback;
		try {
			startActivityForResult(new Intent("android.intent.action.PICK", Media.EXTERNAL_CONTENT_URI), RESULT_PICK_IMAGE);
		} catch (ActivityNotFoundException e) {}
	}

	void setFileDialogCallback(long callback) {
		this.mFileDialogCallback = callback;
	}
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode != RESULT_PICK_IMAGE) {
			return;
		}
		if (resultCode == -1 && data != null) {
			Uri selectedImage = data.getData();
			if (selectedImage != null) {
				String[] filePathColumn = new String[STORAGE_PERMISSION_ID];
				filePathColumn[0] = "_data";
				Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
				cursor.moveToFirst();
				nativeOnPickImageSuccess(this.mCallback, cursor.getString(cursor.getColumnIndex(filePathColumn[0])));
				this.mCallback = 0;
				cursor.close();
			}
		} else if (this.mCallback != 0) {
			nativeOnPickImageCanceled(this.mCallback);
			this.mCallback = 0;
		}
	}

	public void startTextToSpeech(String s) {
		if (this.textToSpeechManager != null)
			this.textToSpeechManager.speak(s, 0, null);
	}

	public void stopTextToSpeech() {
		if (this.textToSpeechManager != null)
			this.textToSpeechManager.stop();
	}

	public boolean isTextToSpeechInProgress() {
		if (this.textToSpeechManager != null)
			return this.textToSpeechManager.isSpeaking();
		return false;
	}
}
